/*
 * @version: 1.0
 * @Author: zhl
 * @Date: 2021-09-26 14:21:35
 * @LastEditors: zhl
 * @LastEditTime: 2022-01-27 15:33:18
 * @Description: 文件实现描述
 */
#include <list>

#include "ParseTask.h"
#include "Server-APDU.h"
#include "Security-APDU.h"
#include "GET-Response.h"
#include "CLogger.h"
#include "HandleData.h"


ParseTask::ParseTask(std::shared_ptr<CMosquittoManager> mm, TASK_PARAMS *task_params, char *apdu, int apdu_len){
    c_mm = mm;
    c_task_params = task_params;
    c_apdu_len = apdu_len;
    c_apdu = (uint8_t *)malloc(apdu_len);
    memcpy(c_apdu, apdu, apdu_len);
}

ParseTask::~ParseTask(){
    if(NULL != c_apdu){
        free(c_apdu);
        c_apdu = NULL;
    }
    c_apdu_len = 0;
    if((NULL != c_task_params) && (!c_task_params->items.empty())){
        c_task_params->items.clear();
    }
}
//
void ParseTask::run(){
    std::list<Data> datas;

    APDU_TAG_TYPE repType = *((APDU_TAG_TYPE *)c_apdu);
    int ret = -1;
    if(repType == SECURITY_RESPONSE){
        ret = Security_APDU::getInstance()->parse_apdu(c_task_params->dev_id, c_apdu+sizeof(APDU_TAG_TYPE), c_apdu_len-sizeof(APDU_TAG_TYPE), datas);
    } else {
        ret = Server_APDU::getInstance().parse_apdu(c_task_params->dev_id, c_apdu, c_apdu_len, datas);
    }

    if(0 < ret){
        for(auto data = datas.begin(); data != datas.end(); data++){
            HandleData::getInstance().handle(c_mm, *data, c_task_params);
            data->destroy();
        }
        datas.clear();
    }
}
